/**
 * 
 */
package com.desksoft.ecommerce.handler.resolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.desksoft.utility.exception.DataAccessTimeoutException;
import com.desksoft.utility.exception.MessageToUIException;

/***************************************
 * <pre>
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: Nov 9, 2011 11:31:30 AM
 * 创建作者：yejw
 * 文件名称：DefaultExceptionResolver.java
 * 版本：1.0
 * 功能：
 * 最后修改时间：Nov 9, 2011 11:31:30 AM
 * 修改记录：
 * </pre>
 *****************************************/
public class DefaultExceptionResolver extends SimpleMappingExceptionResolver {

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
	 * #doResolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		
		//根据请求头判断是否为AJAX请求。
        if (StringUtils.isNotBlank(request.getHeader("X-Requested-With"))){
        	
        	//数据库访问超时
    		if (ex instanceof DataAccessTimeoutException) {
    			response.setHeader("DAO-timeout", "1");
    			genericRespSet(response);
    			
    			return null;
    		}
    		
    		if (ex instanceof MessageToUIException) {
    			response.setHeader("EX-MsgToUI", "1");
    			genericRespSet(response);
    			
    			ModelAndView mav = new ModelAndView(this.determineViewName(ex, request));
    			mav.getModelMap().put("msg", ex.getMessage());
    			
    			return mav;
    		}
        }
        
		return super.doResolveException(request, response, handler, ex);
	}
	
	/**
	 * 
	 * @param response
	 */
	private void genericRespSet(HttpServletResponse response) {
		response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    	response.setContentType("text/html;charset=UTF-8");
	}

}
